<template>
   <div>
        <!-- 面包屑导航 -->
<el-breadcrumb separator="/">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
  <el-breadcrumb-item>参数列表</el-breadcrumb-item>
  </el-breadcrumb>

<el-card>
    <!-- 警告区域 -->
<el-alert
    title="注意:只允许为第三级分类设置相关参数"
    type="warning"
    :closable="false"
    show-icon>
  </el-alert>
  <!-- 选择商品分类区域 -->
    <el-row class="cat_opt">
        <el-col :span="4">
    <div class="sp">选择商品分类:</div>
    <!-- 级联选择器 -->
        </el-col>
    <el-col :span="6">
 <el-cascader
  expand-trigger="hover"
    :props="cateProps"
    v-model="selectedCateKeys"
    :options="catelist"
    @change="handleChange">
    </el-cascader>
        </el-col>
    </el-row>
    <!-- tab 页签 -->
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
    <el-tab-pane label="动态参数" name="many" >
        <!-- 添加参数按钮 -->
        <el-button 
        @click="addDialogVisible=true"
        type="primary" size='mini' :disabled="isBtnDisabled">
        添加参数</el-button>
        <!-- 动态参数表格 -->
        <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
                <!-- 循环渲染tag -->
                <template slot-scope="scope">
                    <el-tag closable 
                    @close="handleClose(i,scope.row)"
                    v-for="(item,i) in scope.row.attr_vals" :key="i"
                    >
                    {{item}}
                    </el-tag>
                    <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index">

            </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" 
                    size="mini"
                    @click="editshow(scope.row.attr_id)"
                    icon="el-icon-edit">编辑</el-button>
                    <el-button type="danger" 
                    @click="deleteshow(scope.row.attr_id)"
                    size="mini"
                    icon="el-icon-delete">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        </el-tab-pane>
    <el-tab-pane label="静态属性" name="only"><el-button 
    @click="addDialogVisible=true"
    type="primary" size='mini' :disabled="isBtnDisabled">
        添加属性</el-button>
        <!-- 静态参数表格 -->
         <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
           <el-table-column type="expand">
                <!-- 循环渲染tag -->
                <template slot-scope="scope">
                    <el-tag closable 
                    @close="handleClose(i,scope.row)"
                    v-for="(item,i) in scope.row.attr_vals" :key="i"
                    >
                    {{item}}
                    </el-tag>
                    <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index">

            </el-table-column>
            <el-table-column label="属性数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" 
                    size="mini"
                    @click="editshow(scope.row.attr_id)"
                    icon="el-icon-edit">编辑</el-button>
                    <el-button type="danger" 
                    @click="deleteshow(scope.row.attr_id)"
                    size="mini"
                    icon="el-icon-delete">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        </el-tab-pane>
  </el-tabs>

</el-card>
<!-- 添加参数的对话框 -->
<el-dialog
  :title="'添加'+titleText"
  :visible.sync="addDialogVisible"
  width="50%"
   @close="addDialogClosed">
 <!-- 添加参数的表单 -->
 <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px"
 >
  <el-form-item :label="titleText" prop="attr_name">
    <el-input v-model="addForm.attr_name"></el-input>
  </el-form-item>
 </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
</el-dialog>
<!-- 编辑对话框 -->
<el-dialog
  title="编辑参数"
  :visible.sync="EditDialogVisible"
  width="50%" @close="editDialogClosed">
  <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px"
 >
  <el-form-item :label="titleText" prop="attr_name">
    <el-input v-model="editForm.attr_name"></el-input>
  </el-form-item>
 </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="EditDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="EditParams">确 定</el-button>
  </span>
</el-dialog>
<!-- 删除对话框 -->
<el-dialog
  title="删除参数"
  :visible.sync="deleteDialogVisible"
  width="50%">
  <span>确认删除参数吗？</span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="deleteDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="deleteParms">确 定</el-button>
  </span>
</el-dialog>
</div>
</template>

<script>
export default {
    data(){
        return{
            //商品分类列表
            catelist:[],
            //级联选择框的配置对象
            cateProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            //级联选择器双向绑定到的数组
            selectedCateKeys:[],
            // 被激活的页签名称
            activeName:'many',
            //动态属性的数据
            manyTableData:[],
            //静态属性的数据
            onlyTableData:[],
            // 对话框的展示
            addDialogVisible:false,
            // 编辑对话框展示
            EditDialogVisible:false,
            // 删除对话框展示
            deleteDialogVisible:false,
            // 添加参数的表单对象
            addForm:{
                attr_name:''
            },
            // 编辑参数表单对象
            editForm:{
                attr_name:''
            },
            // 添加表单的验证规则
            addFormRules:{
                attr_name:[{
                    required:true,message:'请输入用参数名称',trigger:'blur'},
                ]
            },
            // 编辑验证规则
            editFormRules:{
                attr_name:[{
                    required:true,message:'请输入用参数名称',trigger:'blur'},
                ]
            },
            // 属性id
            attr_id:'',
            
        }
    },
created(){
    this.getCateList()
},
methods:{
   async getCateList(){
    const {data:res} = await this.$http.get('categories')
    if(res.meta.status !== 200){
        return this.$message.error('获取商品分类失败')
    }
    this.catelist = res.data
    },
    // 级联选择器选中项触发回调
   handleChange(){
       this.getParamsData()
      
    },
    // tab页签点击事件处理函数
    handleTabClick(){
       this.getParamsData()

    },
   async getParamsData(){
         //证明选中的不是三级分类
        if(this.selectedCateKeys.length !== 3){
            this.selectedCateKeys = []
            this.manyTableData = []
            this.onlyTableData = []
            return
        }
        //证明是三级分类
        //根据所选id和当前所处面板获取对应参数
     const {data:res}=await this.$http.get(`categories/${this.cateID}/attributes`,{params:{sel:this.activeName}})
         if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败!')
      }
      res.data.forEach(item=>{
        item.attr_vals = item.attr_vals ?
       item.attr_vals = item.attr_vals.split(' ') : []
       //添加布尔值控制文本框显示隐藏
       item.inputVisible = false
       item.inputValue = ''
      })
      if(this.activeName === 'many'){
        this.manyTableData = res.data
      }else{
        this.onlyTableData = res.data
      }
    },
    // 监听对话框的关闭事件
    addDialogClosed(){
        this.$refs.addFormRef.resetFields()
    },
    // 添加参数
         addParams(){
          this.$refs.addFormRef.validate(async valid=>{
                    if(!valid)return
                 const {data:res} =  await this.$http.post(`categories/${this.cateID}/attributes`,
                    {attr_name:this.addForm.attr_name,
                    attr_sel:this.activeName})
                    if(res.meta.status!==201)
                    return this.$message.error('添加参数失败!')
                    this.addDialogVisible = false
                    this.getParamsData()
                })
            },
    // 监听编辑对话框关闭事件
    editDialogClosed(){
        this.$refs.editFormRef.resetFields()
    },
    editshow(id){
        this.EditDialogVisible = true
        this.attr_id = id
    },
    deleteshow(id){
        this.deleteDialogVisible = true
        this.attr_id = id
    },
    // 编辑参数
    EditParams(){
          this.$refs.editFormRef.validate(async valid=>{
                    if(!valid)return
                 const {data:res} =  await this.$http.put(`categories/${this.cateID}/attributes/${this.attr_id}`,
                    {attr_name:this.editForm.attr_name,
                    attr_sel:this.activeName})
                    if(res.meta.status!==200)
                    return this.$message.error('编辑参数失败!')
                    this.EditDialogVisible = false
                    this.getParamsData()
                })
    },
    // 删除参数
   async deleteParms(){
       const {data:res} = await this.$http.delete(`categories/${this.cateID}/attributes/${this.attr_id}`)
       if(res.meta.status!==200)
                    return this.$message.error('删除参数失败!')
                    this.deleteDialogVisible = false
                    this.getParamsData()
    },
    // 文本框回调
    handleInputConfirm(row){
        if(row.inputValue.trim().length === 0){row.inputValue = ''
        row.inputVisible = false
        return
        }
        //没有return则说明输入了内容
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        //需要保存操作
         this.saveAttrVals(row)
},
    // 点击按钮展示文本框
    showInput(row){
        row.inputVisible = true
        // 让文本框自动获得焦点
         this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
    },
    // 删除对应可选项
    handleClose(i,row)
    {
        row.attr_vals.splice(i,1)
        this.saveAttrVals(row)
    },
    // 对attr——vals操作保存到数据库
   async saveAttrVals(row){
            const {data:res} =  await this.$http.put(`categories/${this.cateID}/attributes/${row.attr_id}`,
        {attr_name:row.attr_name, attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join(' ')})
         if(res.meta.status!==200)
         return this.$message.error('修改参数项失败!')
        this.$message.success('修改参数项成功')
    
    }
},
computed:{
    //如果按钮需要被禁用则返回true否则返回false
    isBtnDisabled(){
        if(this.selectedCateKeys.length !== 3)
        {return true}
        return false
    },
    cateID(){
        if(this.selectedCateKeys.length === 3){
            return this.selectedCateKeys[2]
        }
        return null
    },
    // 动态计算标题的文本
    titleText(){
        if(this.activeName === 'many')
        {return '动态参数'}
        return '静态属性'
    }
}
}
</script>

<style lang='less' scoped>
.cat_opt{
    margin: 15px ;
}
.sp{
    margin-top:10px ;
}
.input-new-tag{
    width: 120px;
}
</style>